from wxauto import *

import json
import requests
import time

# 获取当前微信客户端
wx = WeChat()

# 目标用户名
target_user = '@空小宝'


def create_jira_issue(summary, description):
    url = "https://worklist.linkingopen.com/rest/api/2/issue/"
    payload = json.dumps({
        "fields": {
            "project": {
                "key": "DTWIN"
            },
            "summary": summary,
            "description": description,
            "issuetype": {
                "name": "任务"
            }
        }
    })
    headers = {
        'Authorization': 'Basic amlhd2VpLm06QWNjcDEyMzQ=',
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    body = json.loads(response.text)
    issue_id = body['id']
    issue_key = body['key']
    # 添加附件
    url = "https://worklist.linkingopen.com/rest/api/2/issue/" + issue_id + '/attachments'

    return issue_key


def rearrange_messages(messages):
    """
    重新排列消息列表，确保图片地址不位于首位。

    :param messages: 消息列表，其中每个元素是一个包含人名和消息（或图片路径）的列表。
    :return: 调整后的消息列表。
    """
    for message in messages:
        # 如果第一条信息是图片，则将其移至最后
        if len(message) > 1 and message[1].endswith('.jpg') or message[1].startswith('/'):
            # 移动图片路径到末尾
            image_path = message.pop(1)
            message.append(image_path)
    return messages


# 首先设置一个监听列表，列表元素为指定好友（或群聊）的昵称
listen_list = [
    '联空Agent测试'
]
# 然后调用`AddListenChat`方法添加监听对象，其中可选参数`savepic`为是否保存新消息图片
for i in listen_list:
    wx.AddListenChat(who=i, savepic=True)

while True:
    time.sleep(30)
    # 监听消息
    msgs = wx.GetListenMessage()

    for chat in msgs:
        # 获取消息内容
        one_msgs = msgs.get(chat)
        key = chat.who

        print('==========one msg ============= ')
        print(one_msgs)
        print('==========one msg ============= ')
        one_msgs = rearrange_messages(one_msgs)

        # 遍历内容
        for one_msg in one_msgs:
            sender = one_msg[0]
            msg = one_msg[1]

            print(f"在 {key} 中找到 {sender} 发送的消息: {msg}")
            msg = msg.replace(target_user, '')
            desc = '群名：' + key + '\n发送人' + sender + '\n内容:' + msg
            issue_id = create_jira_issue(msg, desc)
            issue_href = 'https://worklist.linkingopen.com/browse/' + issue_id

            # 发送消息
            who = '毛佳伟🐳'
            notice_msg = '您有一个新工单:' + issue_href
            wx.SendMsg(notice_msg, who)
